<?php

class Step extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'step':
	 * @var string $id
	 * @var string $label
	 * @var string $description
	 */

	/**
	 * Returns the static model of the specified AR class.
	 * @return CActiveRecord the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'step';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		return array(
			array('label','length','max'=>100),
			array('label, active', 'required'),
			array('active', 'numerical', 'integerOnly'=>true),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'topics' => array(self::HAS_MANY, 'Topic', 'step_id', 'order' => 'orderIndex', 'condition' => 'parent_id is null and active = 1'),
			'allTopics' => array(self::HAS_MANY, 'Topic', 'step_id', 'order' => 'orderIndex', 'condition' => 'parent_id is null'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'Id',
			'label' => 'Label',
			'description' => 'Description',
			'active' => 'Active',
		);
	}
	
	public function getWeeks_number() {
		$weeks_number = 0;
		
		foreach ($this->topics as $topic) {
			if ($topic->weeks_number + $topic->weeks_before > $weeks_number)
				$weeks_number = $topic->weeks_number + $topic->weeks_before;
		}
		
		return $weeks_number;
	}
	
	public function getWeeks_before() {
		return 0;
	}
	
	public function getKey() {
		return 'step_' . $this->id;
	}
	
	public function getParent_key() {
		return '';
	}
	
	public function primaryKey()
	{
		return 'id';
	}
}
